package com.paranoid.flashcard.view;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.paranoid.flashcard.R;
import com.paranoid.flashcard.dao.FlashcardDao;
import com.paranoid.flashcard.logic.DownloadService;
import com.paranoid.flashcard.model.Deck;
import com.paranoid.flashcard.model.Deck.DownloadStatus;

public class DeckListActivity extends Activity {
	ListView mListView;
	FlashcardDao mFlashcardDao;
	SimpleCursorAdapter mAdapter;
	IncomingReceiver mReceiver;
	IntentFilter mIntentFilter;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mReceiver = new IncomingReceiver();
	    mIntentFilter = new IntentFilter();
	    mIntentFilter.addAction(DownloadService.DOWNLOAD_FINISHED_INTENT);
	    
		mFlashcardDao = FlashcardDao.getInstance(this);
		setContentView(R.layout.deck_list);
		mListView = (ListView)findViewById(R.id.deckListView);
		Cursor cursor = mFlashcardDao.getDownloadedDecks();
		mAdapter = new DeckListAdapter(this, R.layout.deck_list_item, cursor, new String[] {Deck.KEY_TITLE}, new int[] {R.id.deck_list_item_description});
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
//				Cursor c = DeckListActivity.this.mAdapter.getCursor();
//				c.moveToPosition(position);
//				if (Deck.getDownloadStatus(c) == DownloadStatus.LOCAL) { 
					DemoPopupWindow dw = new DemoPopupWindow(view, id);
					dw.showLikeQuickAction(0, 30);
//				}
			}
		});
	}
	
	@Override
	protected void onResume() {
		registerReceiver(mReceiver, mIntentFilter);
		mAdapter.getCursor().requery();
		mAdapter.notifyDataSetChanged();
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		unregisterReceiver(mReceiver);
		super.onPause();
	}
	
	public void notifyDownloadFinished() {
		mAdapter.getCursor().requery();
		mAdapter.notifyDataSetChanged();
	}
	
	/**
	 * Extends {@link BetterPopupWindow}
	 * <p>
	 * Overrides onCreate to create the view and register the button listeners
	 * 
	 * @author qbert
	 * 
	 */
	private class DemoPopupWindow extends BetterPopupWindow implements OnClickListener {
		private long mDeckId;
		public DemoPopupWindow(View anchor, long deckId) {
			super(anchor);
			mDeckId = deckId;
		}

		@Override
		protected void onCreate() {
			// inflate layout
			LayoutInflater inflater =
					(LayoutInflater) this.anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			ViewGroup root = (ViewGroup) inflater.inflate(R.layout.popup_grid_layout, null);
			
			View studyView = root.findViewById(R.id.decklist_study);
			studyView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(DeckListActivity.this, CardReviewActivity.class);
					intent.putExtra(Deck.KEY_ID, mDeckId);
					DemoPopupWindow.this.dismiss();
					startActivity(intent);
				}
				
			});

			View deleteView = root.findViewById(R.id.decklist_delete);
			deleteView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(final View v) {
					DemoPopupWindow.this.dismiss();
					AsyncTask<FlashcardDao, Void, Void> deleteTask = new  AsyncTask<FlashcardDao, Void, Void>() {
						@Override
						protected Void doInBackground(FlashcardDao... params) {
							FlashcardDao dao = params[0];
							dao.deleteDeck(mDeckId);
		                    dao.markDeckRemote(mDeckId);
							return null;
						}

						@Override
						protected void onPostExecute(Void result) {
							super.onPostExecute(result);
						}
					};
					mFlashcardDao.markDeckDeleted(mDeckId);
					mAdapter.getCursor().requery();
					mAdapter.notifyDataSetChanged();
					deleteTask.execute(mFlashcardDao);
				}
			});

			View previewView = root.findViewById(R.id.decklist_preview);
			previewView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					DemoPopupWindow.this.dismiss();
					Toast.makeText(v.getContext(), "Coming soon", Toast.LENGTH_SHORT).show();
				}
			});

			// set the inflated view as what we want to display
			this.setContentView(root);
		}

		@Override
		public void onClick(View v) {
			// we'll just display a simple toast on a button click
			Button b = (Button) v;
			Toast.makeText(this.anchor.getContext(), b.getText(), Toast.LENGTH_SHORT).show();
			this.dismiss();
		}
		
		
	}
	
	private class IncomingReceiver extends BroadcastReceiver {
		    @Override
		    public void onReceive(Context context, Intent intent) {
		    	DeckListActivity.this.notifyDownloadFinished();
		        if (intent.getAction().equals(DownloadService.DOWNLOAD_FINISHED_INTENT)) {
		            System.out.println("GOT THE INTENT");
		        }
		    }
		}
}
